package itbour.onetouchshow.base;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.lsjr.utils.NetUtils;
import com.xiao.nicevideoplayer.LogUtil;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.TxVideoPlayerController;

import java.lang.ref.WeakReference;

import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.video.videoplay.helper.video.ViedoPlayChecker;
import itbour.onetouchshow.base.mvp.BasePresenterImpl;
import itbour.onetouchshow.base.mvp.BaseView;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.service.HomeKeyWatcher;
import itbour.onetouchshow.service.NetworkStateService.NetStateChangeEvent;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.StatusBarCompat;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.rxbus.RxBus;
import rx.Subscription;
import rx.functions.Action1;

import static com.xiao.nicevideoplayer.NiceVideoPlayer.STATE_IDLE;

/**
 * 详情模式播放页面基础类
 */
public abstract class BaseIJKPlayActivity<V extends BaseView, T extends BasePresenterImpl<V>> extends MVPBaseActivity<V, T> implements BaseView {

    protected boolean pressedHome;
    protected HomeKeyWatcher mHomeKeyWatcher;
    protected TxVideoPlayerController controller;
    // protected boolean isPlay;
    protected boolean isPause = false;
    protected boolean isallowPlay = true;
    protected boolean isNotreStart = false;
    WeakReference reference;
    /**
     * 注册事件处理
     */
    Subscription subscribe;
    private boolean onHomePlay = false;

    public void baseInit() {
        registerEvent();
        // reference = new WeakReference<>(get);
        getmNiceVideoPlayer().setPlayerType(NiceVideoPlayer.TYPE_NATIVE); // IjkPlayer or MediaPlayer
        controller = new TxVideoPlayerController(this);
        controller.setLooping(isLoopPlay());
        // controller.setImage(R.drawable.place_icon);

        getmNiceVideoPlayer().setController(controller);
        mHomeKeyWatcher = new HomeKeyWatcher(this);
        mHomeKeyWatcher.setOnHomePressedListener(new HomeKeyWatcher.OnHomePressedListener() {
            @Override
            public void onHomePressed() {
                pressedHome = true;
            }
        });
        pressedHome = false;
        mHomeKeyWatcher.startWatch();

        //设置默认高度
        ViewGroup.LayoutParams layoutParams = getmNiceVideoPlayer().getLayoutParams();
        if (layoutParams != null) {
            layoutParams.height = UIUtils.dp2px(230);
            layoutParams.width = UIUtils.WH()[0];
            getmNiceVideoPlayer().setLayoutParams(layoutParams);
        }
    }

    protected boolean isLoopPlay() {
        return true;
    }

    protected void onStartPlay(String viudeUrl, String videoName) {
        setVideoHight();
        if (!TextUtils.isEmpty(viudeUrl)) {
            getmNiceVideoPlayer().setUp(viudeUrl, null);
        }
        if (!TextUtils.isEmpty(videoName)) {
            controller.setTitle(videoName);
        }

    }

    protected void onChageUrlStartPlay(String viudeUrl, String videoName) {
        if (!TextUtils.isEmpty(viudeUrl)) {
            getmNiceVideoPlayer().chageUrlUp(viudeUrl);
        }
        if (!TextUtils.isEmpty(videoName)) {
            controller.setTitle(videoName);
        }

    }

    public void setVideoHight() {
        ViewGroup.LayoutParams layoutParams = getmNiceVideoPlayer().getLayoutParams();
        if (videoHeight() == 0) {
            layoutParams.height = UIUtils.dp2px(250);
        } else {
            layoutParams.height = videoHeight();
        }
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        //  layoutParams.width = UIUtils.WH()[0];
        getmNiceVideoPlayer().setLayoutParams(layoutParams);
    }

    protected abstract int videoHeight();

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        baseInit();
    }

    protected abstract NiceVideoPlayer getmNiceVideoPlayer();

    @Override
    protected void onPause() {

        //L_.e("BaseIJKPlayActivity---onPause");
        //退出后台的状态
        onHomePlay = getmNiceVideoPlayer().isPlaying();
        getmNiceVideoPlayer().pause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onStop() {
        // 在OnStop中是release还是suspend播放器，需要看是不是因为按了Home键
        if (pressedHome) {
            //getmNiceVideoPlayer().pause();
        }
        super.onStop();
        mHomeKeyWatcher.stopWatch();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNotreStart) {
            return;
        }
        if (onHomePlay) {
            if (getmNiceVideoPlayer().isPaused() && isallowPlay) {
                if (NetUtils.is4G(this)) {
                    controller.status4G();
                } else {
                    getmNiceVideoPlayer().restart();
                }
            } else {
                getmNiceVideoPlayer().start();
            }
            isPause = false;
        }
    }

    @Override
    protected void onRestart() {
        mHomeKeyWatcher.startWatch();
        pressedHome = false;
        super.onRestart();
    }

    @Override
    public void onBackPressed() {
        if (onBackPressd()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void setImmersionBarBlack() {
        StatusBarCompat.setStatusBarColor(this, UIUtils.getColor(R.color.app_status_bar_color));
        //4.4 手机全屏状态栏问题
        getmNiceVideoPlayer().setOnWindowChangeListener(new NiceVideoPlayer.OnWindowChangeListener() {
            @Override
            public void enterFullScreen(boolean isFull) {
                if (isFull) {
                    StatusBarCompat.setStatusBarColor(BaseIJKPlayActivity.this, UIUtils.getColor(android.R.color.transparent));
                    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                } else {
                    StatusBarCompat.setStatusBarColor(BaseIJKPlayActivity.this, UIUtils.getColor(itbour.onetouchshow.R.color.app_status_bar_color));
                }
            }
        });
    }

    public boolean onBackPressd() {
        if (getmNiceVideoPlayer() != null) {
            if (getmNiceVideoPlayer().isFullScreen()) {
                return getmNiceVideoPlayer().exitFullScreen();
            } else if (getmNiceVideoPlayer().isTinyWindow()) {
                return getmNiceVideoPlayer().exitTinyWindow();
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if (getmNiceVideoPlayer() != null) {
            getmNiceVideoPlayer().release();
        }
        super.onDestroy();
        if (!subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
    }

    protected void registerEvent() {
        subscribe = RxBus.getDefault().toObserverable(NetStateChangeEvent.class).subscribe(new Action1<NetStateChangeEvent>() {
            @Override
            public void call(NetStateChangeEvent netStateChangeEvent) {
                L_.e("NetStateChangeEvent" + netStateChangeEvent.getState() + "");
                if (isPause && netStateChangeEvent.getState() == NetStateChangeEvent.NetState.NET_WIFI) {
                    return;
                }
                if (netStateChangeEvent.getState() == NetStateChangeEvent.NetState.NET_4G) {
                    //如果在移动网络播放，则提示用户
                    setcheckNetWork();
                    controller.status4G();

                } else if (netStateChangeEvent.getState() == NetStateChangeEvent.NetState.NET_WIFI) {
                    //   checkNetWork();
                    setcheckNetWork();
                    controller.statusWifi();

                } else {
                    controller.statusNoNetWork();
                }
            }
        });

    }

    public void setcheckNetWork() {
        if (!isPause) {
            ViedoPlayChecker.checkPlayNet(this, new ViedoPlayChecker.ActionListener() {
                @Override
                public void doAction() {
                    // NiceVideoPlayerManager.instance().resumeNiceVideoPlayer();
                    // mNiceVideoPlayer.res;
                    LogUtil.i("NetStateChangeEvent");
                    //getmNiceVideoPlayer().restart();
                    controller.status4G();

                }
            }, new ViedoPlayChecker.ActionListener() {
                @Override
                public void doAction() {
                    if (getmNiceVideoPlayer().isInitVideoManager()) {
                        getmNiceVideoPlayer().restart();
                    } else {
                        //重新初始化
                        getmNiceVideoPlayer().setmCurrentState(STATE_IDLE);
                        getmNiceVideoPlayer().start4G();
                    }
                }
            });
        }
    }
}
